package com.lanou3g.zjl.chating.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.lanou3g.zjl.chating.dao.greendao.DaoMaster;
import com.lanou3g.zjl.chating.dao.greendao.DaoSession;
import com.lanou3g.zjl.chating.dao.greendao.UserDao;

/**
 * Created by Risky on 15/10/29.
 */
public class DaoSingleton {
    private static final String DATABASE_NAME = "daodemo.db";
    private volatile static DaoSingleton instance;
    private SQLiteDatabase db;
    private DaoMaster daoMaster;
    private DaoSession daoSession;
    private Context context;
    private DaoMaster.DevOpenHelper helper;
    private UserDao userDao;

    private DaoSingleton(Context mcontext) {

        context = mcontext;
    }

    public static DaoSingleton getInstance(Context context) {
        if (instance == null) {
            synchronized (DaoSingleton.class) {
                if (instance == null) {
                    instance = new DaoSingleton(context);
                }
            }
        }
        return instance;
    }

    public DaoMaster.DevOpenHelper getHelper() {
        if (helper == null) {
            helper = new DaoMaster.DevOpenHelper(context, DATABASE_NAME, null);
        }
        return helper;
    }

    private SQLiteDatabase getDb() {
        if (db == null) {
            db = getHelper().getWritableDatabase();
        }
        return db;
    }

    private DaoMaster getDaoMaster() {
        if (daoMaster == null) {
            daoMaster = new DaoMaster(getDb());
        }
        return daoMaster;
    }

    private DaoSession getDaoSession() {
        if (daoSession == null) {
            daoSession = getDaoMaster().newSession();
        }
        return daoSession;
    }
    // 用户表操作类
    public UserDao getUserDao() {
        if (userDao == null) {
            userDao = getDaoSession().getUserDao();
        }
        return userDao;
    }

}
